#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
    TreeNode *tree = NULL;
    TreeNode *build(vector<int> &postorder, int pl, int pr, vector<int> inorder, int il, int ir)
    {
        if (pl > pr)
            return NULL;
        TreeNode *root = new TreeNode(postorder[pr]);
        int index = il;
        for (index = il; index <= ir; ++index)
        {
            if (inorder[index] == postorder[pr])
                break;
        }
        TreeNode *lchild = NULL, *rchild = NULL;
        lchild = build(postorder, pl, pl + (index - il - 1), inorder, il, index - 1);
        rchild = build(postorder, pl + (index - il), pr - 1, inorder, index + 1, ir);
        root->left = lchild;
        root->right = rchild;
        return root;
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    {
        int len = postorder.size() - 1;
        tree = build(postorder, 0, len, inorder, 0, len);
        return tree;
    }
};